package schema

import (
	"fmt"
	"reflect"

	"gitee.com/fish-afraid-of-water/goes"
	"gitee.com/fish-afraid-of-water/goes/utils"
)

type IndexNamer interface {
	IndexName() string
}

func getIndexName(dest interface{}) (string, error) {

	value := reflect.ValueOf(dest)
	if value.Kind() == reflect.Ptr && value.IsNil() {
		value = reflect.New(value.Type().Elem())
	}
	modelType := reflect.Indirect(value).Type()

	if modelType.Kind() == reflect.Interface {
		modelType = reflect.Indirect(reflect.ValueOf(dest)).Elem().Type()
	}

	for modelType.Kind() == reflect.Slice || modelType.Kind() == reflect.Array || modelType.Kind() == reflect.Ptr {
		modelType = modelType.Elem()
	}

	if modelType.Kind() != reflect.Struct {
		if modelType.PkgPath() == "" {
			return "", fmt.Errorf("%w: %+v", goes.ErrNotSupportIndexName, dest)
		}
		return "", fmt.Errorf("%w: %s.%s", goes.ErrNotSupportIndexName, modelType.PkgPath(), modelType.Name())
	}

	modelValue := reflect.New(modelType)

	indexName := ""
	if namer, ok := modelValue.Interface().(IndexNamer); ok {
		indexName = namer.IndexName()
	}

	if indexName == "" {
		indexName = utils.ToLineName(modelType.Name())
	}

	return indexName, nil
}
